package com.hae.shop.common.util;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * bean转换
 */
public class BeanConvertUtil<E, T> {
        
    public static <E, T> E TToE(T TEntity, Class<E> EClass) {
        // 判断T是否为空!
        if (TEntity == null) {
            return null;
        }
        // 判断EClass 是否为空
        if (EClass == null) {
            return null;
        }
        try {
            E newInstance = EClass.newInstance();
            BeanUtils.copyProperties(TEntity, newInstance);
            // T转换E
            return newInstance;
        } catch (Exception e) {
            return null;
        }
    }
    
    public static <E, T> T EToT(E EEntity, Class<T> TClass) {
        // 判断T是否为空!
        if (EEntity == null) {
            return null;
        }
        // 判断EClass 是否为空
        if (TClass == null) {
            return null;
        }
        try {
            T newInstance = TClass.newInstance();
            BeanUtils.copyProperties(EEntity, newInstance);
            // T转换E
            return newInstance;
        } catch (Exception e) {
            return null;
        }
    }

    public static <E, T> List<T> EListToTList(List<E> EEntityList, Class<T> TClass) {
        // 判断T是否为空!
        if (EEntityList == null) {
            return null;
        }
        // 判断EClass 是否为空
        if (TClass == null) {
            return null;
        }
        //循环转化
        List<T> result = new ArrayList<>();
        for (Object EEntity : EEntityList) {
            try {
                T newInstance = TClass.newInstance();
                BeanUtils.copyProperties(EEntity, newInstance);
                // T转换E
                result.add(newInstance);
            } catch (Exception e) {
                return null;
            }
        }
        return result;
    }

}
